package com.xjm.excption;

import cn.dev33.satoken.exception.NotLoginException;
import com.xjm.entity.vo.Result;
import com.xjm.enums.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@RestControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler
    public Result<String> globalException(Exception e)
    {
        if (e instanceof HttpMessageNotReadableException){
            log.error("参数错误",e);
            return Result.error("请求参数不能为空");
        } else if (e instanceof MethodArgumentNotValidException exception) {
            // 获取异常中的错误信息
            FieldError fieldErrors = exception.getBindingResult().getFieldError();
            if (fieldErrors != null){
                return Result.error(fieldErrors.getField()+":"+fieldErrors.getDefaultMessage());
            }
            return Result.error(e.getMessage());
        }else if (e instanceof AppException){
            return Result.error(e.getMessage());
        } else if (e instanceof NotLoginException) {
            return Result.error(StatusEnum.Unauthorized.code,e.getMessage());
        }else if (e instanceof RedisConnectionFailureException){
            return Result.error(StatusEnum.SystemError.code,"redis连接失败,请启动redis或更换redis源");
        }else if (e instanceof NoResourceFoundException){
            return Result.error(StatusEnum.NotFound.code,"请求地址不存在");
        }
        log.error("系统错误",e);
        return Result.error();
    }
}
